# -*- coding: utf-8 -*-
"""
@Time    : 2024/7/12 15:53 
@Author  : ZhangShenao 
@File    : square_sum_aio.py
@Desc    : asyncio版本——给定一个list,针对计算list中的每一个元素,计算从0开始到该元素的平方和
"""
import asyncio

from bacis.decorator.perf_log_decorator import perf_log


async def calc_square_sum(n: int) -> None:
    """
    异步实现,计算从0开始到n的平方和
    """
    result = sum([i ** 2 for i in range(0, n + 1)])
    print(f'The square sum of {n} is {result}.')


async def calc_all_square_sum(numbers: list[int]) -> None:
    """
    异步实现,给定一个list,针对计算list中的每一个元素,计算从0开始到该元素的平方和
    :param numbers: 元素list
    """

    # 创建异步任务
    tasks = [asyncio.create_task(calc_square_sum(n)) for n in numbers]

    # 等待异步任务执行完成
    await asyncio.gather(*tasks)


@perf_log
def run():
    numbers = [10000000 + x for x in range(20)]
    # 开启EventLoop,调度异步任务
    asyncio.run(calc_all_square_sum(numbers))


run()

# [run] costs 11113.67 ms
